'use strict';
var m = Object.defineProperty;
var g = (i, s, e) =>
  s in i
    ? m(i, s, { enumerable: !0, configurable: !0, writable: !0, value: e })
    : (i[s] = e);
var f = (i, s, e) => (g(i, typeof s != 'symbol' ? s + '' : s, e), e);
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const w = require('../doc/anchors.cjs'),
  v = require('../visit.cjs'),
  l = require('./identity.cjs'),
  A = require('./Node.cjs'),
  d = require('./toJS.cjs');
class p extends A.NodeBase {
  constructor(e) {
    super(l.ALIAS);
    f(this, 'source');
    (this.source = e),
      Object.defineProperty(this, 'tag', {
        set() {
          throw new Error('Alias nodes cannot have tags');
        },
      });
  }
  resolve(e) {
    let t;
    return (
      v.visit(e, {
        Node: (r, o) => {
          if (o === this) return v.visit.BREAK;
          o.anchor === this.source && (t = o);
        },
      }),
      t
    );
  }
  toJSON(e, t) {
    if (!t) return { source: this.source };
    const { anchors: r, doc: o, maxAliasCount: u } = t,
      a = this.resolve(o);
    if (!a) {
      const c = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
      throw new ReferenceError(c);
    }
    let n = r.get(a);
    if ((n || (d.toJS(a, null, t), (n = r.get(a))), !n || n.res === void 0)) {
      const c = 'This should not happen: Alias anchor was not resolved?';
      throw new ReferenceError(c);
    }
    if (
      u >= 0 &&
      ((n.count += 1),
      n.aliasCount === 0 && (n.aliasCount = h(o, a, r)),
      n.count * n.aliasCount > u)
    ) {
      const c = 'Excessive alias count indicates a resource exhaustion attack';
      throw new ReferenceError(c);
    }
    return n.res;
  }
  toString(e, t, r) {
    const o = `*${this.source}`;
    if (e) {
      if (
        (w.anchorIsValid(this.source),
        e.options.verifyAliasOrder && !e.anchors.has(this.source))
      ) {
        const u = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
        throw new Error(u);
      }
      if (e.implicitKey) return `${o} `;
    }
    return o;
  }
}
function h(i, s, e) {
  if (l.isAlias(s)) {
    const t = s.resolve(i),
      r = e && t && e.get(t);
    return r ? r.count * r.aliasCount : 0;
  } else if (l.isCollection(s)) {
    let t = 0;
    for (const r of s.items) {
      const o = h(i, r, e);
      o > t && (t = o);
    }
    return t;
  } else if (l.isPair(s)) {
    const t = h(i, s.key, e),
      r = h(i, s.value, e);
    return Math.max(t, r);
  }
  return 1;
}
exports.Alias = p;
